package com.fingerchar.core.util;

import com.alibaba.fastjson.JSONObject;
import com.fingerchar.core.util.contract.ERC721;
import lombok.extern.slf4j.Slf4j;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.ReadonlyTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.DefaultGasProvider;

import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;

/**
 * @author tangzf
 * @date 2022/9/7
 */
@Slf4j
public class TntWeb3jUtil {

    private static Web3j web3j = Web3j.build(new HttpService("https://bsc-testnet.nodereal.io/v1/ea05893e6278442bb227581875de5d44"));




    public static void main(String[] args) throws IOException {
        //Request req = web3j.ethAccounts();

        //查询账户余额
        //Object result = web3j.ethGetBalance("0x5ab441bb90dc1d8E7Edca95af47af70AA009874B", DefaultBlockParameterName.LATEST).send();

        //查询交易记录
        EthTransaction result = web3j.ethGetTransactionByHash("0x23f6ba067ec1734fb030bcb259db8dc1555c8039106b7b6bc9a07d230a437cd3").send();
        Transaction df = result.getTransaction().orElse(new Transaction());
        //查询发起交易的数量
        //Object result = web3j.ethGetTransactionCount("0x8c7fbf18b38555f088d13ee7a10a9c4299b650a3", DefaultBlockParameterName.LATEST).send();

        //web3j.ethGetFilterLogs()


        System.out.println(JSONObject.toJSON(result));

        //nft操作
//        String nftAdd = "0xa335859d0f5a7c89a9101ebe667dd790d44d0957";
//        String nftUrl = getErc721Uri("0xa335859d0f5a7c89a9101ebe667dd790d44d0957", "1");
//        System.out.println(nftUrl);

    }

    public static String getErc721Uri(String token, String tokenId) {
        TransactionManager transactionManager = new ReadonlyTransactionManager(web3j, token);
        ERC721 contract721 = ERC721.load(token, web3j, transactionManager, new DefaultGasProvider());
        try {
            return contract721.tokenURI(new BigInteger(tokenId)).sendAsync().get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("获取721uri异常", e);
            return null;
        }
    }




}
